<?php

namespace Library;
use Library\Prizes\Prizes;
use Library\Prizes\Hongbao;
use Library\Prizes\Ad;
use Library\Prizes\Link;
use Library\Prizes\Entity;
use Think\Log;

/**
 * 摇一摇获取奖品
 *
 * @author pufan
 */
class HuodongShake {
    protected $card;
	protected $card_model;
    protected $card_events;
    protected $firstVisit;
    protected $chosenBeacon;
    protected $curWxPageId;
    protected $curEvent;  //当前活动
    protected $curCard;  //当前物料
    protected $curOpenid;
    protected $event_type;

    // $event_type 为1,为摇一摇 2为扫一扫
    public function __construct($event_type = 1) {
        $this->card = \Library\CardCode::getInstance();
		$this->card_model= D("Card");
        $this->card_events= D("Events");

        $this->firstVisit = false;
        $this->curOpenid = $_SESSION['open_id'];
        $this->event_type = $event_type;
    }

    public function isFirst() {
        return $this->firstVisit;
    }

    /*
     * 检查该账户是否被限制 例如：12小时内最多摇3次
     */
    public function check_limit() {
    }

    /*
     * 奖品统计
     */
    public function shakeAnalytics($prizes) {
        $analysislog = C('LOG_REAL_PATH')."/Analysis/".date('y_m_d').'.log';

        $device = $this->get_current_Beacon();
        unset($device['$device']);

        $tongji = $device;
        if ($this->curWxPageId) {
            $tongji['pageid'] = $this->curWxPageId;
        } else {
            $tongji['pageid'] = 0;
        }
        $tongji['openid'] = $this->curOpenid;
        if ($this->curEvent) {
            $tongji['eid'] = $this->curEvent['id'];
            $tongji['etype'] = $this->curEvent['event_type'];
        } else {
            $tongji['eid'] = 0;
            $tongji['etype'] = 0;
        }
        if ($this->curCard) {
            $tongji['cid'] = $this->curCard['id'];
            $tongji['ctype'] = $this->curCard['card_type'];
        } else {
            $tongji['cid'] = 0;
            $tongji['ctype'] = 0;
        }
        $tongji['time'] = date('Y-m-d H:i:s', time());

        if (!is_null($prizes)) {
            \Think\Log::write(json_encode(array_merge($tongji,  $prizes)), 'JSON', NULL, $analysislog);
        } else {
            \Think\Log::write(json_encode($tongji), 'JSON', NULL, $analysislog);
        }
    }

    //获取奖品,
    public function get_prizes() {
        $event = $this->get_current_event();
        Log::record(json_encode($event));

        if (!empty($event) && is_array($event)) {
            $card = $this->get_materials($event);
            $desc['openid'] = $this->curOpenid;
            $desc['event_id'] = $event['id'];
            \Think\Log::record('card:'. json_encode($card));

            if (!empty($card) && is_array($card)) {
                $this->curCard = $card;
                $desc['card_id'] = $card['id'];

                switch ($card['card_type']) {
                    case 1: //红包
                        $desc['congratulations'] = $card['congratulations'];
                        $desc['center_pic'] = $card['card_icon'];
                        $desc['center_url'] = $card['card_url'];
                        $desc['prizes_grade'] = $card['prizes_grade'];
                        $prizes = new Hongbao($desc);
                        break;
                    case 2: //核销
                        $prizes = NULL;
                        break;
                    case 3: //链接
                        \Think\Log::record('link');
                        $desc['ad_id'] = $card['id'];
                        $desc['center_pic'] = $card['card_icon'];
                        $desc['center_url'] = $card['card_url'];
                        $desc['title'] = $card['congratulations'];
                        $desc['description'] = $card['card_intro'];
                        $desc['prizes_grade'] = $card['prizes_grade'];
                        $prizes = new Link($desc);
                        break;
                    case 4: //广告
                        $desc['card_id'] = $card['id'];
                        $desc['title'] = $card['congratulations'];
                        $desc['description'] = $card['card_intro'];
                        $desc['center_pic'] = $card['card_icon'];
                        $desc['center_url'] = $card['card_url'];

                        $prizes = new Ad($desc);
                        break;
                    case 5: //实物
                        \Think\Log::record('Entity');
                        $desc['center_pic'] = $card['card_icon'];
                        $desc['center_url'] = $card['card_url'];
                        $desc['title'] = $card['congratulations'];
                        $desc['description'] = $card['card_intro'];
                        $desc['prizes_grade'] = $card['prizes_grade'];
                        $prizes = new Entity($desc);
                        break;
                    default:
                        break;
                }
            }
            /*
             * 没有抽中奖品或者抽中的奖品是无效的,返回一个广告
             */
            if ($prizes == NULL || $prizes->is_valid() == FALSE) {
                $ad = $this->get_ad($event);
                if (!empty($ad) && is_array($ad)) {
                    $this->curCard = $card;
                    $desc['card_id'] = $ad['id'];
                    $desc['title'] = $ad['congratulations'];
                    $desc['description'] = $ad['card_intro'];
                    $desc['center_pic'] = $ad['card_icon'];
                    $desc['center_url'] = $ad['card_url'];

                    $prizes = new Ad($desc);
                } else {
                    return NULL;
                }
            }
            return $prizes;
        } else {
            \Think\Log::record('没有抽中的活动');
        }
        return NULL;
    }

    private function is_beijing() {
        $user = User::getInstance();
        $location = $user->getUserLocation();
        $bjLocation = C('BJ_AREA');
        Log::record(($location['latitude']));
        Log::record($location['longitude']);
        Log::record($bjLocation['0']);

        if ($location) {
            if ($bjLocation['0'] > $location['latitude'] && $bjLocation['2'] < $location['latitude'] &&
                $bjLocation['1'] > $location['longitude'] && $bjLocation['3'] < $location['longitude']) {
                return true;
            }
        }
        return false;
    }

    //获取物料, 包含广告
    private function get_materials($event) {
        if ($this->event_type == 1) {
            $chosenBeacon = $this->get_current_Beacon();
            if ($chosenBeacon == false) {
                Log::record('chosenBeacon empty');
                return false;
            }
        }
        $is_beijing = $this->is_beijing();
        Log::record(json_encode($is_beijing));
        /*
         * 根据活动获取奖品信息，卡券，广告，红包
         */
        if (isset($event['bind_cards']) && !empty($event['bind_cards'])) {
            $datetime = date("Y-m-d H:i:s",time());

            if ($this->event_type == 1) {
                $sql = 'SELECT
                        *,
                        COUNT(*)
                    FROM
                        (
                            SELECT
                                DISTINCT yy_card.*
                            FROM
                                yy_card
                                LEFT JOIN yy_user_prizes_count ON (
                                    yy_card.id = yy_user_prizes_count.card_id
                                    AND yy_user_prizes_count.openid = "' . $_SESSION['open_id'] . '"
                                )
                                LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                AND yy_card_area.type = 0
                                LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.province_id
                                OR yy_card_area.area_id = yy_store.city_id
                                OR yy_card_area.area_id = 100000
                            	LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                            WHERE
                                yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                AND yy_card.id in (' . $event['bind_cards'] . ')
                                AND yy_card.start_at  <= "' . $datetime . '"
                                AND yy_card.end_at >= "' . $datetime . '"
                                AND yy_card.card_count > yy_card.card_get_count
                                AND (
                                    yy_card.card_count_day > yy_card.card_get_count_day
                                    OR yy_card.card_count_day = 0
                                )
                                AND (
                                    (yy_user_prizes_count.cur_day_num is not null AND
                                    yy_card.day_count_limit_by_user > yy_user_prizes_count.cur_day_num)
                                    OR yy_card.day_count_limit_by_user = 0
                                    OR yy_user_prizes_count.cur_day_num is null
                                )
                                AND (
                                    (yy_user_prizes_count.total_num is not null AND
                                    yy_card.count_limit_by_user > yy_user_prizes_count.total_num)
                                    OR yy_card.count_limit_by_user = 0
                                    OR yy_user_prizes_count.total_num is null
                                )
                                AND yy_card.card_status = 1
                            UNION ALL
                            SELECT
                                *
                            FROM
                                (
                                    (
                                        SELECT
                                            DISTINCT yy_card.*
                                        FROM
                                            yy_card
                                            LEFT JOIN yy_user_prizes_count ON (
                                                yy_card.id = yy_user_prizes_count.card_id
                                                AND yy_user_prizes_count.openid = "' . $_SESSION['open_id'] . '"
                                            )
                                            LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                            AND yy_card_area.type = 2
                                            LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.stype
                                            OR yy_card_area.area_id = 0
                            				LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                                        WHERE
                                            yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                            AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                            AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                            AND yy_card.id in (' . $event['bind_cards'] . ')
                                            AND yy_card.start_at  <= "' . $datetime . '"
                                            AND yy_card.end_at >= "' . $datetime . '"
                                            AND yy_card.card_count > yy_card.card_get_count
                                            AND (
                                                yy_card.card_count_day > yy_card.card_get_count_day
                                                OR yy_card.card_count_day = 0
                                            )
                                             AND (
                                                (yy_user_prizes_count.cur_day_num is not null AND
                                                yy_card.day_count_limit_by_user > yy_user_prizes_count.cur_day_num)
                                                OR yy_card.day_count_limit_by_user = 0
                                                OR yy_user_prizes_count.cur_day_num is null
                                            )
                                            AND (
                                                (yy_user_prizes_count.total_num is not null AND
                                                yy_card.count_limit_by_user > yy_user_prizes_count.total_num)
                                                OR yy_card.count_limit_by_user = 0
                                                OR yy_user_prizes_count.total_num is null
                                            )
                                            AND yy_card.card_status = 1
                                    )
                                    UNION
                                        (
                                            SELECT
                                                DISTINCT yy_card.*
                                            FROM
                                                yy_card
                                                LEFT JOIN yy_user_prizes_count ON (
                                                    yy_card.id = yy_user_prizes_count.card_id
                                                    AND yy_user_prizes_count.openid = "' . $_SESSION['open_id'] . '"
                                                )
                                                LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                                AND yy_card_area.type = 1
                                                LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.stype
                            					LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                                            WHERE
                                                yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                                AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                                AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                                AND yy_card.id in (' . $event['bind_cards'] . ')
                                                AND yy_card.start_at  <= "' . $datetime . '"
                                                AND yy_card.end_at >= "' . $datetime . '"
                                                AND yy_card.card_count > yy_card.card_get_count
                                                AND (
                                                    yy_card.card_count_day > yy_card.card_get_count_day
                                                    OR yy_card.card_count_day = 0
                                                )
                                                AND (
                                                    (yy_user_prizes_count.cur_day_num is not null AND
                                                    yy_card.day_count_limit_by_user > yy_user_prizes_count.cur_day_num)
                                                    OR yy_card.day_count_limit_by_user = 0
                                                    OR yy_user_prizes_count.cur_day_num is null
                                                )
                                                AND (
                                                    (yy_user_prizes_count.total_num is not null AND
                                                    yy_card.count_limit_by_user > yy_user_prizes_count.total_num)
                                                    OR yy_card.count_limit_by_user = 0
                                                    OR yy_user_prizes_count.total_num is null
                                                )
                                                AND yy_card.card_status = 1
                                        )
                                ) bq
                        ) all_card
                    GROUP BY
                        id
                    HAVING
                        COUNT(*) > 1';
            } else if ($this->event_type == 2) {
                $sql = 'SELECT
                            DISTINCT yy_card.* , yy_card_huodong_extend.prizes_grade
                        FROM
                            yy_card
                            LEFT JOIN yy_user_prizes_count ON (
                                yy_card.id = yy_user_prizes_count.card_id
                                AND yy_user_prizes_count.openid = "' . $_SESSION['open_id'] . '"
                            )
                            LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                            AND yy_card_area.type = 0
                            LEFT JOIN yy_card_huodong_extend ON yy_card_huodong_extend.card_id = yy_card.id
                        WHERE
                            yy_card.id in (' . $event['bind_cards'] . ')
                            AND yy_card.start_at  <= "' . $datetime . '"
                            AND yy_card.end_at >= "' . $datetime . '"
                            AND yy_card.card_count > yy_card.card_get_count
                            AND (
                                    yy_card.card_count_day > yy_card.card_get_count_day
                                    OR yy_card.card_count_day = 0
                                )
                            AND (
                                (yy_user_prizes_count.cur_day_num is not null AND
                                yy_card.day_count_limit_by_user > yy_user_prizes_count.cur_day_num)
                                OR yy_card.day_count_limit_by_user = 0
                                OR yy_user_prizes_count.cur_day_num is null
                            )
                            AND (
                                (yy_user_prizes_count.total_num is not null AND
                                yy_card.count_limit_by_user > yy_user_prizes_count.total_num)
                                OR yy_card.count_limit_by_user = 0
                                OR yy_user_prizes_count.total_num is null
                            )
                            AND yy_card.card_status = 1
                            AND (yy_card_area.area_id = 100000
                                OR (yy_card_area.area_id = 110000
                                AND '.(int)$is_beijing.' = 1))';
            }
            $cards = $this->card_events->query($sql);
            Log::record($sql);

            if ($cards && is_array($cards)) {
                $bind_cards = explode(',', $event['bind_cards']);
                $bind_cards_percentage = explode(',', $event['bind_cards_percentage']);

                $count = count($bind_cards);
                if ($count === count($bind_cards_percentage)) {
                    $shark_cards = array();
                    for($i = 0; $i < $count; $i++) {
                        foreach ($cards as $c) {
                            if ($c['id'] == $bind_cards[$i]) {
                                $c['weight'] = $bind_cards_percentage[$i];
                                $shark_cards[] = $c;

                                break;
                            }
                        }
                    }
                    Log::record(json_encode($shark_cards).'weight'. $event['total_weight']);
                    return $this->rand_by_weight($shark_cards, 'weight', $event['total_weight']);
                } else {
                    \Think\Log::record('抽中的活动物料列表和中奖概率列表不匹配');
                }
            } else {
                \Think\Log::record('抽中的活动没有匹配的物料');
            }
        } else {
            \Think\Log::record('抽中的活动没有绑定物料');
        }

        return NULL;
    }

    //根据活动获取广告
    private function get_ad($event) {
        $chosenBeacon = $this->get_current_Beacon();
        if (isset($event['bind_cards']) && !empty($event['bind_cards'])) {
            $datetime = date("Y-m-d H:i:s",time());
            if ($this->event_type == 1) {
                $sql = 'SELECT
                        *,
                        COUNT(*)
                    FROM
                        (
                            SELECT
                                DISTINCT yy_card.*
                            FROM
                                yy_card
                                LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                AND yy_card_area.type = 0
                                LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.province_id
                                OR yy_card_area.area_id = yy_store.city_id
                                OR yy_card_area.area_id = 100000
                            	LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                            WHERE
                                yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                AND yy_card.id in (' . $event['bind_cards'] . ')
                                AND yy_card.start_at  <= "' . $datetime . '"
                                AND yy_card.end_at >= "' . $datetime . '"
                                AND yy_card.card_count > yy_card.card_get_count
                                AND (
                                    yy_card.card_count_day > yy_card.card_get_count_day
                                    OR yy_card.card_count_day = 0
                                )
                                AND yy_card.card_type = 4
                                AND yy_card.card_status = 1
                            UNION ALL
                            SELECT
                                *
                            FROM
                                (
                                    (
                                        SELECT
                                            DISTINCT yy_card.*
                                        FROM
                                            yy_card
                                            LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                            AND yy_card_area.type = 2
                                            LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.stype
                                            OR yy_card_area.area_id = 0
                            				LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                                        WHERE
                                            yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                            AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                            AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                            AND yy_card.id in (' . $event['bind_cards'] . ')
                                            AND yy_card.start_at  <= "' . $datetime . '"
                                            AND yy_card.end_at >= "' . $datetime . '"
                                            AND yy_card.card_count > yy_card.card_get_count
                                            AND (
                                                yy_card.card_count_day > yy_card.card_get_count_day
                                                OR yy_card.card_count_day = 0
                                            )
                                            AND yy_card.card_type = 4
                                            AND yy_card.card_status = 1
                                    )
                                    UNION
                                        (
                                            SELECT
                                                DISTINCT yy_card.*
                                            FROM
                                                yy_card
                                                LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                                AND yy_card_area.type = 1
                                                LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.stype
                            					LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                                            WHERE
                                                yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                                AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                                AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                                AND yy_card.id in (' . $event['bind_cards'] . ')
                                                AND yy_card.start_at  <= "' . $datetime . '"
                                                AND yy_card.end_at >= "' . $datetime . '"
                                                AND yy_card.card_count > yy_card.card_get_count
                                                AND (
                                                    yy_card.card_count_day > yy_card.card_get_count_day
                                                    OR yy_card.card_count_day = 0
                                                )
                                                AND yy_card.card_type = 4
                                                AND yy_card.card_status = 1
                                        )
                                ) bq
                        ) all_card
                    GROUP BY
                        id
                    HAVING
                        COUNT(*) > 1';
            } elseif ($this->event_type == 2) {
                $sql = 'SELECT
                        *,
                        COUNT(*)
                    FROM
                        (
                            SELECT
                                DISTINCT yy_card.*
                            FROM
                                yy_card
                                LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                AND yy_card_area.type = 0
                                LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.province_id
                                OR yy_card_area.area_id = yy_store.city_id
                                OR yy_card_area.area_id = 100000
                            WHERE
                                yy_card.id in (' . $event['bind_cards'] . ')
                                AND yy_card.start_at  <= "' . $datetime . '"
                                AND yy_card.end_at >= "' . $datetime . '"
                                AND yy_card.card_count > yy_card.card_get_count
                                AND (
                                    yy_card.card_count_day > yy_card.card_get_count_day
                                    OR yy_card.card_count_day = 0
                                )
                                AND yy_card.card_type = 4
                                AND yy_card.card_status = 1
                            UNION ALL
                            SELECT
                                *
                            FROM
                                (
                                    (
                                        SELECT
                                            DISTINCT yy_card.*
                                        FROM
                                            yy_card
                                            LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                            AND yy_card_area.type = 2
                                            LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.stype
                                            OR yy_card_area.area_id = 0
                                        WHERE
                                            yy_card.id in (' . $event['bind_cards'] . ')
                                            AND yy_card.start_at  <= "' . $datetime . '"
                                            AND yy_card.end_at >= "' . $datetime . '"
                                            AND yy_card.card_count > yy_card.card_get_count
                                            AND (
                                                yy_card.card_count_day > yy_card.card_get_count_day
                                                OR yy_card.card_count_day = 0
                                            )
                                            AND yy_card.card_type = 4
                                            AND yy_card.card_status = 1
                                    )
                                    UNION
                                        (
                                            SELECT
                                                DISTINCT yy_card.*
                                            FROM
                                                yy_card
                                                LEFT JOIN yy_card_area ON yy_card.id = yy_card_area.card_id
                                                AND yy_card_area.type = 1
                                                LEFT JOIN yy_store ON yy_card_area.area_id = yy_store.stype
                                            WHERE
                                                yy_card.id in (' . $event['bind_cards'] . ')
                                                AND yy_card.start_at  <= "' . $datetime . '"
                                                AND yy_card.end_at >= "' . $datetime . '"
                                                AND yy_card.card_count > yy_card.card_get_count
                                                AND (
                                                    yy_card.card_count_day > yy_card.card_get_count_day
                                                    OR yy_card.card_count_day = 0
                                                )
                                                AND yy_card.card_type = 4
                                                AND yy_card.card_status = 1
                                        )
                                ) bq
                        ) all_card
                    GROUP BY
                        id
                    HAVING
                        COUNT(*) > 1';
            }
            $cards = $this->card_events->query($sql);

            if ($cards && is_array($cards)) {
                if (count($cards) == 1) {
                    return $cards[0];
                } else {
                    $bind_cards = explode(',', $event['bind_cards']);
                    $bind_cards_percentage = explode(',', $event['bind_cards_percentage']);

                    $count = count($bind_cards);
                    if ($count === count($bind_cards_percentage)) {
                        $shark_cards = array();
                        for($i = 0; $i < $count; $i++) {
                            foreach ($cards as $c) {
                                if ($c['id'] == $bind_cards[$i]) {
                                    $c['weight'] = $bind_cards_percentage[$i];
                                    $shark_cards[] = $c;
                                    break;
                                }
                            }
                        }
                        unset($cards);
                        return $this->rand_by_weight($shark_cards, 'weight');
                    } else {
                        \Think\Log::record('抽中的活动广告列表和中奖概率列表不匹配');
                    }
                }
            } else {
                \Think\Log::record('抽中的活动没有匹配的广告');
            }
        } else {
            \Think\Log::record('抽中的活动没有绑定广告');
        }

        return NULL;
    }

    public function getShakeInfo() {
        $shakeInfo = Wx::getShakeInfoShakeAroundUser($_GET['ticket']);
        if ($shakeInfo != false) {
            //首字母大写是微信推送事件的风格
            $beaconInfo['Uuid'] =  $shakeInfo['data']['beacon_info']['uuid'];
            $beaconInfo['Major'] =  $shakeInfo['data']['beacon_info']['major'];
            $beaconInfo['Minor'] =  $shakeInfo['data']['beacon_info']['minor'];
            $beaconInfo['Mark'] = md5(json_encode($shakeInfo));

            $Info['beaconInfo'] = $beaconInfo;
            $Info['page'] = $shakeInfo['data']['page_id'];
            $Info['openid'] = $shakeInfo['data']['openid'];
            return $Info;
        }
        return false;
    }

    /*
     * 根据入口id和摇一摇进入的Ibeacan, 随机获取一个活动
     */
    public function get_activity_by_pageId() {

        if ($this->event_type == 1) {
            $shakeInfo = $this->getShakeInfo();
            Log::record('shakeInfo' . json_encode($shakeInfo));
            if ($shakeInfo['openid'] != $this->curOpenid || empty($shakeInfo['beaconInfo']) || empty($shakeInfo['page'])) {
                return false;
            }
            $chosenBeacon = $shakeInfo['beaconInfo'];
            $this->curWxPageId = $shakeInfo['page'];
        } else if ($this->event_type == 2) {
            $this->curWxPageId = $_GET['activityid'];
        }

        /*
         *  微信事件推送方式,获取用户信息。
         * $this->curWxPageId = $_GET['activityid'];
           $chosenBeacon = $this->get_current_Beacon_by_page();
        */
        $datetime = date("Y-m-d H:i:s",time());
        if ($this->event_type == 1) {
            $sql = 'SELECT
                    *,
                    COUNT(*)
                FROM
                    (
                        SELECT
                            DISTINCT yy_events.*
                        FROM
                            yy_events
                            LEFT JOIN yy_event_area ON (
                                yy_events.id = yy_event_area.event_id
                                AND yy_event_area.type = 0
                            )
                            LEFT JOIN yy_store ON yy_event_area.area_id = yy_store.province_id
                            OR yy_event_area.area_id = yy_store.city_id
                            OR yy_event_area.area_id = 100000
                            LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                        WHERE
                            yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                            AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                            AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                            AND yy_events.wx_page_id = "' . $this->curWxPageId . '"
                            AND yy_events.start_at  <= "' . $datetime . '"
                            AND yy_events.end_at >= "' . $datetime . '"
                            AND yy_events.bind_cards != ""
                            AND yy_events.event_status = 2
                            AND yy_events.event_type = 1
                        UNION ALL
                        SELECT
                            *
                        FROM
                            (
                                (
                                    SELECT
                                        DISTINCT yy_events.*
                                    FROM
                                        yy_events
                                        LEFT JOIN yy_event_area ON (
                                            yy_events.id = yy_event_area.event_id
                                            AND yy_event_area.type = 2
                                        )
                                        LEFT JOIN yy_store ON yy_event_area.area_id = yy_store.stype
                                        OR yy_event_area.area_id = 0
                            			LEFT JOIN yy_device ON yy_device.store_id = yy_store.store_id
                                    WHERE
                                        yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                        AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                        AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                        AND yy_events.wx_page_id = "' . $this->curWxPageId . '"
                                        AND yy_events.start_at  <= "' . $datetime . '"
                                        AND yy_events.end_at >= "' . $datetime . '"
                                        AND yy_events.bind_cards != ""
                                        AND yy_events.event_status = 2
                                        AND yy_events.event_type = 1
                                )
                                UNION
                                    (
                                        SELECT
                                            DISTINCT yy_events.*
                                        FROM
                                            yy_events
                                            LEFT JOIN yy_event_area ON (
                                                yy_events.id = yy_event_area.event_id
                                                AND yy_event_area.type = 1
                                            )
                                            LEFT JOIN yy_groups_device ON (
                                                yy_groups_device.aid = yy_event_area.area_id
                                            )
                                            LEFT JOIN yy_device ON (
                                                yy_groups_device.bid = yy_device.id
                                            )
                                        WHERE
                                            yy_device.uuid = "' . $chosenBeacon['Uuid'] . '"
                                            AND yy_device.major = "' . $chosenBeacon['Major'] . '"
                                            AND yy_device.minor = "' . $chosenBeacon['Minor'] . '"
                                            AND yy_events.wx_page_id = "' . $this->curWxPageId . '"
                                            AND yy_events.start_at  <= "' . $datetime . '"
                                            AND yy_events.end_at >= "' . $datetime . '"
                                            AND yy_events.bind_cards != ""
                                            AND yy_events.event_status = 2
                                            AND yy_events.event_type = 1
                                    )
                            ) bq
                    ) all_event
                GROUP BY
                    id
                HAVING
                    COUNT(*) > 1';
        } elseif ($this->event_type == 2) {
            $sql = 'SELECT
                    *,
                    COUNT(*)
                FROM
                    (
                        SELECT
                            DISTINCT yy_events.*
                        FROM
                            yy_events
                            LEFT JOIN yy_event_area ON (
                                yy_events.id = yy_event_area.event_id
                                AND yy_event_area.type = 0
                            )
                            LEFT JOIN yy_store ON yy_event_area.area_id = yy_store.province_id
                            OR yy_event_area.area_id = yy_store.city_id
                            OR yy_event_area.area_id = 100000
                        WHERE
                            yy_events.wx_page_id = "' . $this->curWxPageId . '"
                            AND yy_events.start_at  <= "' . $datetime . '"
                            AND yy_events.end_at >= "' . $datetime . '"
                            AND yy_events.bind_cards != ""
                            AND yy_events.event_status = 2
                            AND yy_events.event_type = 2
                        UNION ALL
                        SELECT
                            *
                        FROM
                            (
                                (
                                    SELECT
                                        DISTINCT yy_events.*
                                    FROM
                                        yy_events
                                        LEFT JOIN yy_event_area ON (
                                            yy_events.id = yy_event_area.event_id
                                            AND yy_event_area.type = 2
                                        )
                                        LEFT JOIN yy_store ON yy_event_area.area_id = yy_store.stype
                                        OR yy_event_area.area_id = 0
                                    WHERE
                                        yy_events.wx_page_id = "' . $this->curWxPageId . '"
                                        AND yy_events.start_at  <= "' . $datetime . '"
                                        AND yy_events.end_at >= "' . $datetime . '"
                                        AND yy_events.bind_cards != ""
                                        AND yy_events.event_status = 2
                                        AND yy_events.event_type = 2
                                )
                                UNION
                                    (
                                        SELECT
                                            DISTINCT yy_events.*
                                        FROM
                                            yy_events
                                            LEFT JOIN yy_event_area ON (
                                                yy_events.id = yy_event_area.event_id
                                                AND yy_event_area.type = 1
                                            )
                                            LEFT JOIN yy_groups_device ON (
                                                yy_groups_device.aid = yy_event_area.area_id
                                            )
                                            LEFT JOIN yy_device ON (
                                                yy_groups_device.bid = yy_device.id
                                            )
                                        WHERE
                                            yy_events.wx_page_id = "' . $this->curWxPageId . '"
                                            AND yy_events.start_at  <= "' . $datetime . '"
                                            AND yy_events.end_at >= "' . $datetime . '"
                                            AND yy_events.bind_cards != ""
                                            AND yy_events.event_status = 2
                                            AND yy_events.event_type = 2
                                    )
                            ) bq
                    ) all_event
                GROUP BY
                    id
                HAVING
                    COUNT(*) > 1';
        }
        $eventList = $this->card_events->query($sql);
        Log::record(json_encode($eventList));

        if (is_array($eventList) && count($eventList) > 0) {
            $event = $this->rand_by_weight($eventList, 'event_weight_factor');

            if ($event) {
                $shark_ts_old = S('shake_event_ts:'.$this->curOpenid);

                if ($this->event_type == 1) {
                    if (empty($shark_ts_old) || $shark_ts_old['ChosenBeacon']['Mark'] != $chosenBeacon['Mark']) {
                        $this->firstVisit = true;
                    }
                    Log::record($shark_ts_old['ChosenBeacon']['Mark'].':'.$chosenBeacon['Mark']);

                    $shark_ts['ChosenEvent'] = $event;
                    $shark_ts['ChosenBeacon'] = $chosenBeacon;
                    $shark_ts['ChosenPage'] = $this->curWxPageId;
                    S('shake_event_ts:'.$this->curOpenid, $shark_ts, C('WX_SHAKE_TIMEOUT'));
                } elseif ($this->event_type == 2) {
                    Log::record('event_type 2');
                    $shark_ts['ChosenEvent'] = $event;
                    $shark_ts['ChosenPage'] = $this->curWxPageId;
                    S('shake_event_ts:'.$this->curOpenid, $shark_ts, C('WX_SCAN_TIMEOUT'));
                }
                return $event;
            }
        }

        if ($this->event_type == 1) {
            $shark_ts['ChosenBeacon'] = $chosenBeacon;
            $shark_ts['ChosenPage'] = $this->curWxPageId;
            S('shake_event_ts:' . $this->curOpenid, $shark_ts, C('WX_SHAKE_TIMEOUT'));
        }
        return false;
    }

    /*
     * 获取当前的活动
     */
    public function get_current_event() {
        $shark_ts = S('shake_event_ts:'.$this->curOpenid);
        $datetime = date("Y-m-d H:i:s",time());

        if ($shark_ts) {
            if (!empty($shark_ts['ChosenEvent']['id'])) {
                $sql = 'SELECT
                            DISTINCT yy_events.*
                        FROM
                            yy_events
                        WHERE
                            yy_events.wx_page_id = "'.$shark_ts['ChosenPage'].'"
                            AND yy_events.start_at  <= "'.$datetime. '"
                            AND yy_events.end_at >= "'.$datetime. '"
                            AND yy_events.bind_cards != ""
                            AND yy_events.event_status = 2
                            AND yy_events.id = '.$shark_ts['ChosenEvent']['id'];

                $eventList = $this->card_events->query($sql);
                if (is_array($eventList) && count($eventList) == 1) {
                    $this->curEvent = $eventList[0];
                    return $this->curEvent;
                }
            }
        }
        return false;
    }

    /*
     * 获取当前的iBeacon
     */
    public function get_current_Beacon() {
        $shark_ts = S('shake_event_ts:'.$this->curOpenid);
        if ($shark_ts) {
            $this->chosenBeacon = $shark_ts['ChosenBeacon'];
            return $shark_ts['ChosenBeacon'];
        }
        return false;
    }

    /*
     * 获取当前的iBeacon
     */
    public function get_current_Beacon_by_page() {
        $shark_ts = S('shake_event_ts:'.$this->curOpenid);
        if ($shark_ts == false) {
            return false;
        }

        foreach($shark_ts['ChosenPageList'] as $chosenPage) {
            if ($chosenPage['ChosenPageId'] == $this->curWxPageId) {
                $this->chosenBeacon = $chosenPage['ChosenBeacon'];
                return $this->chosenBeacon;
            }
        }
        return false;
    }

    /*
     *  根据权重，随机获取$rand_pool中的值.
     *  根据$rand_pool中的权重，随机获取值。 匹配的概率为  总权重／单项权重  ， 总权重设定为100
     *  $rand_pool
     *  $weight_key_name 为权重字段名称
     */
    private function rand_by_100weight(array $rand_pool, $weight_key_name) {
        $map_pool = array();
        $accuracy = 10000000000;  //小数点后10位
        $totalWeight = 99.9999999999 * $accuracy;

        $rand = mt_rand(0, $totalWeight);
        $start = 0;
        $end = 0;

        $weightSum=0;

        Log::record('rand:'.$rand);
        foreach($rand_pool as $entity) {
            $start = $end;
            $end += $entity[$weight_key_name] * $accuracy;
            $weightSum += $entity[$weight_key_name];
            if ($rand >= $start && $rand < $end) {
                return $entity;
            }
        }
        Log::record('weightSum:'. $weightSum);

        return NULL;
    }

    /*
     *  根据权重，随机获取$rand_pool中的值.
     *  根据$rand_pool中的权重，随机获取值。 匹配的概率为  总权重／单项权重
     *  $rand_pool
     *  $weight_key_name 为权重字段名称
     */
    private function rand_by_weight(array $rand_pool, $weight_key_name, $eventTotalWeight = 0) {
        $accuracy = 1000000;  //小数点后6位

        $map_pool = array();
        $limit = 0;
        $totalWeight = 0;
        foreach($rand_pool as $entity) {
            $map_entity = array();
            $map_entity['start'] = $limit;
            $limit += $entity[$weight_key_name] * $accuracy;
            $map_entity['end'] = $limit;
            $map_entity['card'] = $entity;

            $totalWeight = $map_entity['end'];
            $map_pool[] = $map_entity;
        }
        if ($eventTotalWeight * $accuracy  > $totalWeight) {
            $totalWeight = $eventTotalWeight * $accuracy;
        }
        $totalWeight--;
        $rand = mt_rand(0, $totalWeight);

        foreach($map_pool as $map_entity) {
            if ($rand >= $map_entity['start'] && $rand < $map_entity['end']) {
                return $map_entity['card'];
                break;
            }
        }
        return NULL;
    }

    //总权重为100时， 随机测试函数。
    public function test_rand_by_weight_group() {
        $this->test_real_rand_by_weight();

        /*$accuracy = 1000000;  //小数点后6位
        $rand_weight1 = mt_rand(0, 50*$accuracy)/$accuracy;
        $rand_weight2 = mt_rand(0, 50*$accuracy)/$accuracy;

        $this->test_rand_by_weight($rand_weight1, $rand_weight2);

        $rand_weight1 = 1000;
        $rand_weight2 = 1000;

        $this->test_rand_by_weight($rand_weight1, $rand_weight2);

        $rand_weight1 = 0.001;
        $rand_weight2 = 0.01;

        $this->test_rand_by_weight($rand_weight1, $rand_weight2);

        $rand_weight1 = 0;
        $rand_weight2 = 99.999999;
        $this->test_rand_by_weight($rand_weight1, $rand_weight2);*/
    }

    private function test_rand_by_weight($rand_weight1, $rand_weight2) {
        $tongji = array();
        $input_array = array (
            array('id' => '1', 'w' => $rand_weight1),
            array('id' => '2', 'w' => $rand_weight2),
        );
        $i =  10000000;
        while ($i>0) {
            $rand = $this->rand_by_weight($input_array, 'w', 100);
            $tongji[$rand['id']]++;
            $i--;
        }
        print_r($input_array);
        var_dump($tongji);
        echo '<br>';
    }

    private function test_real_rand_by_weight() {
        set_time_limit(0);//0表示不限时
        $tongji = array();

        $prizesJson  = '[{"id":"106","card_name":"\u6982\u7387\u6d4b\u8bd51- 5%","card_status":"1","congratulations":"\u606d\u559c\u4f60\u83b7\u5f97\u5956\u54c11","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682080206470.jpeg","card_url":"","card_intro":"\u606d\u559c\u4f60\u83b7\u5f97\u5956\u54c11","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:26:00","end_at":"2016-07-18 11:26:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:52:32","updated_at":"2016-07-11 15:52:32","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"","userid":"1","ugid":"0","count(*)":"2","weight":"105"},{"id":"107","card_name":"\u6d4b\u8bd5\u7269\u65992-5%","card_status":"1","congratulations":"\u606d\u559c\u83b7\u5f97\u5956\u54c12","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682081259194.jpeg","card_url":"","card_intro":"\u606d\u559c\u83b7\u5f97\u5956\u54c12","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:34:00","end_at":"2016-07-18 11:34:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:52:21","updated_at":"2016-07-11 15:52:21","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"","userid":"1","ugid":"0","count(*)":"2","weight":"5"},{"id":"108","card_name":"\u6d4b\u8bd5\u7269\u65993-10%","card_status":"1","congratulations":"\u606d\u559c\u4f60\u83b7\u5f97\u5956\u54c13","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682083614488.jpeg","card_url":"https:\/\/zb.weixin.qq.com\/","card_intro":"\u606d\u559c\u4f60\u83b7\u5f97\u5956\u54c13","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:37:00","end_at":"2016-07-18 11:37:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:52:17","updated_at":"2016-07-11 15:52:17","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"15110162900","userid":"1","ugid":"0","count(*)":"2","weight":"10"},{"id":"109","card_name":"\u6d4b\u8bd5\u7269\u65994-10%","card_status":"1","congratulations":"\u6d4b\u8bd5\u7269\u65994-10%","card_type":"1","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682084327799.jpeg","card_url":"","card_intro":"\u6d4b\u8bd5\u7269\u65994-10%","card_count":"1000","card_get_count":"4","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:39:00","end_at":"2016-07-18 11:39:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:52:07","updated_at":"2016-07-11 15:52:07","wx_cardid":null,"min_money":"1","max_money":"1","yj_num":"1","yj_phone":"","userid":"1","ugid":"0","count(*)":"2","weight":"10"},{"id":"110","card_name":"\u6d4b\u8bd5\u7269\u65995-15\uff05","card_status":"1","congratulations":"\u6d4b\u8bd5\u7269\u65995-15\uff05","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682085327943.jpeg","card_url":"http:\/\/www.baidu.com","card_intro":"\u6d4b\u8bd5\u7269\u65995-15\uff05","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:40:00","end_at":"2016-07-18 11:40:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:52:01","updated_at":"2016-07-11 15:52:01","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"1","userid":"1","ugid":"0","count(*)":"2","weight":"15"},{"id":"111","card_name":"\u6d4b\u8bd5\u7269\u65996\uff0d25%","card_status":"1","congratulations":"\u6d4b\u8bd5\u7269\u65996\uff0d25%","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682086981184.jpeg","card_url":"http:\/\/www.baidu.com","card_intro":"\u6d4b\u8bd5\u7269\u65996\uff0d25%","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:43:00","end_at":"2016-07-18 11:43:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:51:53","updated_at":"2016-07-11 15:51:53","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"15110162900","userid":"1","ugid":"0","count(*)":"2","weight":"25"},{"id":"112","card_name":"\u6d4b\u8bd5\u7269\u65997\uff0d10%","card_status":"1","congratulations":"\u6d4b\u8bd5\u7269\u65997\uff0d10%","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682088027378.jpeg","card_url":"http:\/\/www.baidu.com","card_intro":"\u6d4b\u8bd5\u7269\u65997\uff0d10%","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:46:00","end_at":"2016-07-18 11:46:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:51:46","updated_at":"2016-07-11 15:51:46","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"15110162900","userid":"1","ugid":"0","count(*)":"2","weight":"10"},{"id":"113","card_name":"\u6d4b\u8bd5\u7269\u65998-20%","card_status":"1","congratulations":"\u6d4b\u8bd5\u7269\u65998-20%","card_type":"5","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/07\/14682088830007.jpeg","card_url":"http:\/\/www.baidu.com","card_intro":"\u6d4b\u8bd5\u7269\u65998-20%","card_count":"100","card_get_count":"0","count_limit_by_user":"100","day_count_limit_by_user":"2","start_at":"2016-07-11 11:46:00","end_at":"2016-07-18 11:46:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-07-11 15:51:41","updated_at":"2016-07-11 15:51:41","wx_cardid":null,"min_money":"0","max_money":"0","yj_num":"1","yj_phone":"15110162900","userid":"1","ugid":"0","count(*)":"2","weight":"20"}]';
        $prizesJson  = '[{"id":"137","card_name":"\u5168\u56fd\u6d3b\u52a8","card_status":"1","congratulations":"\u6d4b\u8bd5\u5927\u5956\u54e6","card_type":"1","create_by":"1","password":"0","card_icon":"img\/Materials\/2016\/08\/14708166662367.png","card_url":" ","card_intro":"\u6d4b\u8bd5\u5927\u5956\u54e6","card_count":"100","card_get_count":"6","card_count_day":"10","card_get_count_day":"6","count_limit_by_user":"20","day_count_limit_by_user":"20","start_at":"2016-08-02 16:09:00","end_at":"2016-08-31 16:09:00","bind_location":"100000|||\u5168\u56fd","deleted_at":null,"created_at":"2016-08-10 16:47:35","updated_at":"2016-08-10 16:47:35","min_money":"1","max_money":"1","yj_num":null,"yj_phone":null,"external_cardid":"","count(*)":"2","weight":"5"}]';
        $prizes = json_decode($prizesJson, true);
        foreach ($prizes as $one) {
            echo $one['id'].':'.$one['weight'].',';
        }
        echo '<br>';
        $i =  10000000;
        while ($i>0) {
            $rand = $this->rand_by_weight($prizes, 'weight', 100);
            $tongji[$rand['id']]++;
            $i--;
        }
        var_dump($tongji);
    }
}
